<?php

namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\PartCompany;
use App\Models\PartCompanyClassify;
use App\Models\PhotoArchives;
use App\Models\PhotoClassify;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;

/**
 * 分类目录服务层
 * Class PhotoClassifyService
 * @package App\Services
 */
class PhotoClassifyService extends BaseService
{
    /**
     * 保存一个照片分类目录
     *
     * @param $params
     * @return bool
     * @author: lxk
     * @date: 2024/3/15 9:14
     */
    public function saveData($params) : bool
    {
        $title      = format_str($params['title']);
        $archivesNo = format_archives_no($params['archives_no']);
        $info = PhotoClassify::query()->where('part_company_id', $params['part_company_id'])
            ->where('title', $title)
            ->orWhere('archives_no', $archivesNo)
            ->first();
        if ($info && ($info->id != $params['id'])) throw new ApiException('名称或档号已存在！');
        if ($params['id']) {
            $photoClassify = PhotoClassify::query()->where('id', $params['id'])->first();
        } else {
            $photoClassify = new PhotoClassify();
            $photoClassify->parent_id = to_int($params['parent_id']);
        }
        $photoClassify->project_id      = $params['project_id'];
        $photoClassify->part_company_id = $params['part_company_id'];
        $photoClassify->title           = format_str($params['title']);
        $photoClassify->archives_no     = format_archives_no($params['archives_no']);
        $photoClassify->creator_id      = user_id();

        return $photoClassify->save();
    }

    /**
     * 更新一条信息
     */
    public function updateData($id, $params)
    {
        $photoClassify = PhotoClassify::query()->where('id', $id)->first();
        $photoClassify->title       = $params['title'];
        $photoClassify->archives_no = format_archives_no($params['archives_no']);
        $photoClassify->creator_id  = user_id();

        return $photoClassify->save();
    }

    /**
     * 获取档案号
     */
    public static function getBaseArchivesNo($photoClassifyId)
    {
        $photoClassify = PhotoClassify::query()->find($photoClassifyId);

        return $photoClassify->archives_no;
    }

    /**
     * 判断是否有下级
     */
    public static function isHaveChild($photoClassifyId)
    {
        return PhotoClassify::query()->where('parent_id', $photoClassifyId)->first();
    }

    /**
     * 获取一条数据信息
     */
    public function getInfo($id)
    {
        return PhotoClassify::query()
            ->where('id', $id)
            ->select('id', 'title', 'parent_id', 'archives_no')
            ->first()
            ->toArray();
    }

    /**
     * 照片分类左侧栏
     *
     * @param $partCompanyId
     * @return \array[][]
     * @throws ApiException
     * @author: lxk
     * @date: 2024/3/20 16:39
     */
    public function treeList($partCompanyId) : array
    {
        $list = PhotoClassify::query()
            ->where('part_company_id', $partCompanyId)
            ->select('id', 'title', 'parent_id', 'archives_no')
            ->get();

        if ($list->isEmpty()) {
            return [
                'list' => [
                    [
                        'id'          => 'firstNode',
                        'node_key'    => 'firstNode',
                        'title'       => '照片档案',
                        'parent_id'   => 0,
                        'archives_no' => '',
                        'children'    => [],
                        'photo_classify_id' => 'firstNode',
                    ]
                ]
            ];
        }
        $list = $list->toArray();
        foreach ($list as &$val) {
            $photoClassifyId          = $val['id'];
            $photoArchiveInstance     = $this->getPhotoArchiveInstance($partCompanyId, $photoClassifyId);
            $val['data_count']        = $photoArchiveInstance->where('photo_classify_id', $photoClassifyId)->count();
            $val['photo_classify_id'] = $photoClassifyId;
        }
        Cache::put('index_id', 0);
        $treeList = PhotoClassifyService::getPhotoClassifyData($list, 0);
        $result   = $this->formatChildrenId($treeList);
        Cache::forget('index_id');

        return [
            'list' => [
                [
                    'id'          => 'firstNode',
                    'node_key'    => '"firstNode"',
                    'title'       => '照片档案',
                    'parent_id'   => 0,
                    'archives_no' => '',
                    'children'    => $result,
                    'photo_classify_id' => 'firstNode',
                ]
            ]
        ];
    }

    /**
     * 最终数据将 id进行格式化，保证id唯一 （前端需要）
     */
    public function formatChildrenId($data)
    {
        foreach ($data as &$val) {
            $val['node_key'] = Cache::increment('index_id');
            if (isset($val['children']) && !empty($val['children'])) {
                $val['children'] = $this->formatChildrenId($val['children']);
            }
        }

        return $data;
    }

    /**
     * 获取照片分类树
     */
    public static function getPhotoClassifyData($list, $id)
    {
        $tree = [];
        foreach ($list as $value) {
            if ($value['parent_id']==$id) {
                $value['children'] = self::getPhotoClassifyData($list, $value['id']);
                if ($value['children']) {
                    $value['data_count'] = '';
                } else {
                    unset($value['children']);
                }
                $tree[] = $value;
            }
        }
        return $tree;
    }

    /**
     * 添加照片档案
     */
    public function addPhotoArchives($params)
    {
        $photoArchivesNo = new PhotoClassify();
        $photoArchivesNo->photo_classify_id = $params['photo_classify_id'];
        $photoArchivesNo->title           = $params['title'];
        $photoArchivesNo->archives_no     = $params['archives_no'];
        $photoArchivesNo->store_period    = $params['store_period'];
        $photoArchivesNo->page_num        = $params['page_num'];
        $photoArchivesNo->start_date      = $params['start_date'] ?? '';
        $photoArchivesNo->end_date        = $params['end_date'] ?? '';
        $photoArchivesNo->part_company_id = $params['part_company_id'];

        return $photoArchivesNo->save();
    }

    /**
     * 回收站列表
     */
    public function PhotoClassifyRecycle($request): array
    {
        $thisQuery = PhotoClassify::onlyTrashed(); //只获取软删除的数据

        if ($request->filled('keyword')) { //判断参数是否存在并且不为空
            $keyword = $request->input('keyword');
            $thisQuery->where('title', 'like', "%{$keyword}%"); //由于不同的表字段不同，所以单独拿出来
        }

        return $this->formatRecycleData($request, $thisQuery);
    }

}
